package com.example.action;

import com.example.bean.User;
import com.example.service.UserService;
import com.example.util.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@MultipartConfig
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = UUIDUtils.getId();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String telephone = req.getParameter("telephone");
        String sex = req.getParameter("sex");
        String date = req.getParameter("birthday");
        String photo = req.getParameter("picture");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = sdf.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User(id, username, password, name, email, telephone, birthday, sex, 0, photo);
        UserService userService = new UserService();
        int n = userService.insertUser(user);
        if (n == -1) {
            req.setAttribute("infomation", "用户已注册");
            req.setAttribute("url", "login.jsp");
            req.setAttribute("second", 5);
            req.getRequestDispatcher("tip.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("index").forward(req, resp);
        }
    }
}
